package cn.samir.sudoku.ui;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import cn.samir.sudoku.R;
import cn.samir.sudoku.adapter.RankListAdapter;
import cn.samir.sudoku.core.RankBean;
import cn.samir.sudoku.keys.Conf;
import cn.samir.sudoku.net.NetTask;
import cn.samir.sudoku.net.OnNetListener;
import cn.samir.sudoku.util.LogUtils;
import cn.samir.sudoku.util.Utils;
import cn.samir.sudoku.view.CircleImageView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;

public class RankActivity extends BaseActivity implements
		OnRefreshListener<ListView>, OnClickListener, OnLastItemVisibleListener {

	PullToRefreshListView pullToRefreshListView;
	ListView mListView;
	ArrayList<RankBean> rankItems = new ArrayList<RankBean>();
	RankListAdapter rankListAdapter;
	CircleImageView mHeadView;
	TextView mTvUserName;
	TextView mTvInfo;
	ImageView iv_start;
	TextView tvTitle;
	boolean isRefreshing = false;
	Context mContext = this;
	Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			
			case 3:
				if (msg.obj != null) {
					rankItems.addAll((ArrayList<RankBean>) msg.obj);
					rankListAdapter.clear();
					rankListAdapter.appendToList(rankItems);
				}
				isRefreshing = false;
				LogUtils.i(TAG, "isRefreshing");
				pullToRefreshListView.onRefreshComplete();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_rank);
		initViews();
		syncRankData(0);
	}

	private void initViews() {
		mHeadView = getView(R.id.civ_icon);
		mTvInfo = getView(R.id.tv_scoreinfo);
		mTvUserName = getView(R.id.tv_username);
		iv_start = getView(R.id.iv_start);
		iv_start.setOnClickListener(this);
		tvTitle = getView(R.id.tv_title);
		tvTitle.setText("排行榜");
		initMyInfoDispaly();
		pullToRefreshListView = getView(R.id.pull_refresh_list);
		mListView = pullToRefreshListView.getRefreshableView();
		pullToRefreshListView.setOnRefreshListener(this);
		pullToRefreshListView.setOnLastItemVisibleListener(this);

		rankListAdapter = new RankListAdapter(this);
		Collections.sort(rankItems);
		rankListAdapter.appendToList(rankItems);
		mListView.setAdapter(rankListAdapter);
	}

	private void initMyInfoDispaly() {

		if (Utils.isLogin(this)) {
			ImageLoader.getInstance().displayImage(
					Utils.getUserBigHeaderUrl(mContext), mHeadView);
			mTvUserName.setText(Utils.getUserName(this));
			mHeadView.setOnClickListener(null);
			mTvInfo.setText("总积分：" + Utils.getUserAllScore(mContext));
		} else {
			showUnregist();
		}
	}

	public void showUnregist() {
		mHeadView.setImageResource(R.drawable.login);
		mHeadView.setOnClickListener(this);
		mTvUserName.setText("未登录");
		mTvInfo.setText("");
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		String label = DateUtils.formatDateTime(getApplicationContext(),
				System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
						| DateUtils.FORMAT_SHOW_DATE
						| DateUtils.FORMAT_ABBREV_ALL);
		// Update the LastUpdatedLabel
		refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
		syncRankData(rankItems.size());
	}

	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.civ_icon:
			loginQQ();
			break;

		case R.id.iv_start:
			finish();
			break;
		default:
			break;
		}

	}

	/**
	 * ﻿{"status":1,"data":[{"usericon":
	 * "http:\/\/sudokus.sinaapp.com\/uh\/8.jpg",
	 * "nickname":"\u52a0\u7070\u732b"
	 * ,"total":"30470","totalkind":"20","gender":"m"}, {"usericon":
	 * "http:\/\/sudokus.sinaapp.com\/uh\/9.jpg","nickname":"\u91d1\u8272\u9633
	 * \u5149 " , "total":"29255","totalkind":"30","gender":"m"},{"usericon":
	 * "http:\/\/sudokus.sinaapp.com\/uh\/7.jpg",
	 * "nickname":"\u74dc\u54e5","total":"24070","totalkind":"20","gender":"m"},
	 * {"usericon":
	 * "http:\/\/sudokus.sinaapp.com\/uh\/6.jpg","nickname":"\u7b49\u5f85\u4f60
	 * \u56de \u6765
	 * " , "total":"18670","totalkind":"20","gender":"m"},{"usericon":
	 * "http:\/\/sudokus.sinaapp.com\/uh\/5.jpg",
	 * "nickname":"\u5927\u7c73","total":"14270","totalkind":"20","gender":"m"},
	 * {"usericon":
	 * "http:\/\/sudokus.sinaapp.com\/uh\/4.jpg","nickname":"Desperado",
	 * "total":"10870","totalkind":"20","gender":"m"},{"usericon":
	 * "http:\/\/sudokus.sinaapp.com\/uh\/3.jpg",
	 * "nickname":"\u6211\u5728\u5730\u72f1"
	 * ,"total":"8470","totalkind":"20","gender":"m"}, {"usericon":
	 * "http:\/\/sudokus.sinaapp.com\/uh\/2.jpg","nickname":"\u65e5\u4e45\u89c1
	 * \u4eba \u5fc3
	 * " , "total":"7200","totalkind":"21","gender":"m"},{"usericon":
	 * "http:\/\/sudokus.sinaapp.com\/uh\/1.jpg",
	 * "nickname":"\u65b0\u95fb\u8054\u64ad"
	 * ,"total":"2416","totalkind":"1","gender":"m"}, {"usericon":
	 * "http:\/\/q.qlogo.cn\/qqapp\/1104439164\/5BAEF44CF5696ACC38C0CC877789865C\/
	 * 1 0 0
	 * " , "nickname":"\u611a\u516c\u79fb\u5c71","total":"900","totalkind":"3" ,
	 * "gender":"m"}]}
	 * 
	 * @param start_rank
	 */
	public void syncRankData(int start_rank) {
		if (isRefreshing)
			return;
		isRefreshing = true;
		NetTask netTask = new NetTask(this);
		HashMap<String, String> maps = new HashMap<String, String>();
		maps.put("requestcode", 10007 + "");
		maps.put("start_rank", start_rank + "");
		netTask.url(Conf.info_url).addParams(maps).doGet(new OnNetListener() {

			@Override
			public void onSuccess(InputStream in) {

			}

			@Override
			public void onSuccess(String result) {
				LogUtils.i(TAG, result);
				ArrayList<RankBean> ranks = null;
				if (!TextUtils.isEmpty(result)) {
					try {
						JSONObject jsonObject = new JSONObject(result);

						int status = jsonObject.getInt("status");
						if (1 == status) {
							String data = jsonObject.getString("data");
							JSONArray jsonArray = new JSONArray(data);
							int count = 0;
							if (jsonArray != null) {
								count = jsonArray.length();
							}
							/**
							 * {"usericon":
							 * "http:\/\/sudokus.sinaapp.com\/uh\/1.jpg" ,
							 * "nickname":"\u65b0\u95fb\u8054\u64ad",
							 * "total":"2416","totalkind":"1","gender":"m"},
							 */
							ranks = new ArrayList<RankBean>();
							for (int i = 0; i < count; i++) {
								String dataString = jsonArray.getString(i);
								JSONObject jsonObject2 = new JSONObject(
										dataString);

								int totalscore = jsonObject2.getInt("total");
								String gender = jsonObject2.getString("gender");
								String nickname = jsonObject2
										.getString("nickname");
								String usericon = jsonObject2
										.getString("usericon");
								int totalkind = jsonObject2.getInt("totalkind");
								RankBean bean = new RankBean(nickname,
										usericon, totalkind, totalscore);
								bean.gender = gender;
								ranks.add(bean);
							}

						}
					} catch (JSONException E) {
						E.printStackTrace();
					}
				}

				Message msg = Message.obtain();
				msg.what = 3;
				msg.obj = ranks;
				handler.sendMessage(msg);
			}

			@Override
			public void onError(String result) {
				Message msg = Message.obtain();
				msg.what = 3;
				msg.obj = null;
				handler.sendMessage(msg);
			}
		});
		;
	}

	@Override
	public void onLastItemVisible() {
		syncRankData(rankItems.size());
	}
}
